package com.bee.common.core.jsonview;


import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.bee.common.core.jsonview.JsonViews.BaseView;

import java.lang.annotation.Annotation;

/**
 * Decorator that detects a declared {@link ResponseView}, and injects support
 * if required
 * 
 * @author martypitt
 * 
 */
public class ViewInjectingReturnValueHandler implements
		HandlerMethodReturnValueHandler {

	private final HandlerMethodReturnValueHandler delegate;

	
	public ViewInjectingReturnValueHandler(
			HandlerMethodReturnValueHandler delegate) {
		this.delegate = delegate;
	}

	@Override
	public boolean supportsReturnType(MethodParameter returnType) {
		return delegate.supportsReturnType(returnType);
	}

	@Override
	public void handleReturnValue(Object returnValue,
			MethodParameter returnType, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest) throws Exception {
		// if the return value is already defined with view type, then no need to wrap it again
		if(!(returnValue instanceof DataWithView)){
			Class<? extends BaseView> viewClass = getDeclaredViewClass(returnType);
			if (viewClass != null) {
				returnValue = wrapResult(returnValue, viewClass);
			}else if(returnType.hasMethodAnnotation(PrivilegeView.class)){
				returnValue = wrapResult(returnValue, viewClass);
			}
		}
		if(returnValue == null){
			returnValue = new ObjectMapper().createObjectNode();
		}

		delegate.handleReturnValue(returnValue, returnType, mavContainer, webRequest);
	}

	/**
	 * Returns the view class declared on the method, if it exists. Otherwise,
	 * returns null.
	 * 
	 * @param returnType
	 * @return
	 */
	private Class<? extends BaseView> getDeclaredViewClass(
			MethodParameter returnType) {
		ResponseView annotation = returnType.getMethodAnnotation(ResponseView.class);
		if (annotation != null) {
			return annotation.value();
		} else {
			return null;
		}
	}

	private Object wrapResult(Object result, Class<? extends BaseView> viewClass) {
		DataWithView response = new DataWithView(result, viewClass);
		return response;
	}
}